package interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Model.GeneralUser;
import Model.permission.Permission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import utils.permission.ConstantsUtils.SessionObj;

import java.util.List;

public class AuthorityInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String searchUri = httpServletRequest.getRequestURI();
        if(searchUri == null){
            return true;
        }
        if(o instanceof HandlerMethod){
//            System.out.println("true");
            HttpSession session = httpServletRequest.getSession();
            GeneralUser onlineUser = (GeneralUser)(session.getAttribute(SessionObj.CURRENT_USER));
            if(onlineUser == null){
                System.out.println("重定向");
                //重定向到login
                httpServletResponse.sendRedirect("/login.jsp");
                return false;
            }
            //TODO: 测试管理员不需要权限校验
            if(onlineUser.getRole_id() == 0){
                return true;
            }
            //判断权限

            List<Permission> permissions = onlineUser.getPermissions();
            for(Permission each: permissions){
                String path =each.getPath();
                if(path == null){continue;}
                if(searchUri.indexOf(path) == 0){
                    if(searchUri.length() == path.length() || searchUri.charAt(path.length()) == '/'){
//                        System.out.printf("匹配uri: %s, 匹配目标:%s\n", searchUri, path);
                        return true;
//                        break;
                    }

                }

            }
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            System.out.printf("拒接请求: %s\n", searchUri);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
